﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using AsNum.Common.EntLib.Validation.CustomValidator.Configuration;

namespace AsNum.Common.EntLib.Validation.CustomValidator {
    [ConfigurationElementType ( typeof ( NotNullOrEmptyValidatorData ) )]
    public class NotNullOrEmptyValidator : Validator<string> {

        private bool negated;
        private string messageTemplate = "";
        private string tag;
        private bool trim;

        public NotNullOrEmptyValidator(string messageTemplate , string tag)
            : base ( messageTemplate , tag ) {
        }

        public NotNullOrEmptyValidator(bool negated , string messageTemplate , string tag , bool trim)
            : base ( messageTemplate , tag ) {
            this.negated = negated;
            this.messageTemplate = messageTemplate;
            this.tag = tag;
            this.trim = trim;
        }

        protected override void DoValidate(string objectToValidate , object currentTarget , string key , ValidationResults validationResults) {
            if ( objectToValidate != null && this.trim ) {
                objectToValidate = objectToValidate.Trim ( );
            }

            if ( string.IsNullOrEmpty ( objectToValidate ) == !this.negated ) {
                LogValidationResult ( validationResults , GetMessage ( objectToValidate , key ) , currentTarget , key );
            }
        }

        protected override string DefaultMessageTemplate {
            get {
                if ( this.negated ) {
                    return CustomValidatorReason.NonNullOrEmptyNegatedValidatorDefaultMessageTemplate;
                } else {
                    return CustomValidatorReason.NonNullOrEmptyNonNegatedValidatorDefaultMessageTemplate;
                }
            }
        }
    }
}
